package com.cgsd.heyu.ui.task;

import android.os.Bundle;

import com.apkfuns.logutils.LogUtils;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.entity.EventMessage;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.ui.home.fragment.WrapperSendFragment;
import com.cgsd.heyu.ui.task.adapter.TaskChildAdapter;
import com.cgsd.heyu.ui.task.vo.TaskListVo;
import com.cgsd.heyu.utils.CommonTools;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.widgets.refresh.NestedRefreshLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/1 14:39
 * Email: xcode126@126.com
 * Desc:任务列表
 */
public class TaskChildFragment extends WrapperSendFragment implements BaseQuickAdapter.RequestLoadMoreListener, NestedRefreshLayout.OnRefreshListener {

    private NestedRefreshLayout mNestedRefreshLayout;
    private RecyclerView mRecyclerView;

    private TaskChildAdapter childAdapter;
    private int page, totalPage, tid, cid;

    public static TaskChildFragment newInstance(int tid) {
        TaskChildFragment fragment = new TaskChildFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("tid", tid);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.common_refresh;
    }

    @Override
    protected void initView() {
        tid = getArguments().getInt("tid");
        initAdapter();
    }

    @Override
    protected void initData() {
        onRefresh();
    }

    @Override
    public void onRefresh() {
        getList(page = 1);
    }

    @Override
    public void onRefresh(Object t) {
        this.cid = (int) t;
        onRefresh();
    }

    @Override
    public void onLoadMoreRequested() {
        if (page < totalPage) {
            getList(++page);
        } else {
            childAdapter.loadMoreEnd(true);
        }
    }

    /**
     * get list
     */
    public void getList(int page) {
        RequestBody requestBody = new RequestParams()
                .putUid()
                .put("page", page)
//                .put("tid", tid)
                .putWithoutEmpty("cid", cid)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .getTaskList(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<TaskListVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<TaskListVo> baseResponse) {
                        LogUtils.e("任务列表："+baseResponse.toString());
                        processList(baseResponse.getBizBody());
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        handleErrorAction(error);
                        //LogUtils.e("任务列表："+error.getBody().toString());
                    }
                });
    }

    /**
     * process list
     *
     * @param listVo
     */
    private void processList(TaskListVo listVo) {
        if (page == 1) {
            totalPage = CommonTools.getTotalPage(listVo.count, AppConfig.PAGE_SIZE);
            if (listVo.count <= 0||listVo.tasklist.size()<=0) {
                childAdapter.getData().clear();
                childAdapter.setEmptyView(getHelperView(mRecyclerView, R.layout.common_empty, null));
                childAdapter.notifyDataSetChanged();
            } else {
                childAdapter.setNewData(listVo.tasklist);
            }
            mNestedRefreshLayout.refreshFinish();
        } else {
            childAdapter.addData(listVo.tasklist);
            childAdapter.loadMoreComplete();
        }
    }

    /**
     * init adapter
     */
    private void initAdapter() {
        mNestedRefreshLayout = findViewById(R.id.mNestedRefreshLayout);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        mNestedRefreshLayout.setOnRefreshListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        childAdapter = new TaskChildAdapter();
        mRecyclerView.setAdapter(childAdapter);
        childAdapter.setOnLoadMoreListener(this, mRecyclerView);
        childAdapter.setOnItemClickListener((adapter, view, position) -> {
            TaskListVo.TasklistBean item = childAdapter.getItem(position);
            startActivity(TaskDetailActivity.getIntent(mContext, item.id));
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        if (event.getCode() == Constants.EventCode.TASK_REFRESH) {
            onRefresh();
        }
    }
}
